package com.dl.mall.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dl.mall.entity.Brand;
import com.dl.mall.mapper.BrandMapper;
import com.dl.mall.service.admin.BrandService_Admin;
import com.dl.mall.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author DL
 * @create 2022-04-19 15:02
 */
@Service
public class BrandServiceImpl_Admin implements BrandService_Admin {

    @Resource
    private BrandMapper brandMapper;

    /**
     * 根据 id 查询品牌判断是否存在，防止品牌重复
     * @param categoryId 分区id
     * @return 是否存在
     */
    @Override
    public boolean isExistBrand(Integer categoryId, String brandName) {
        return brandMapper.queryBrandByIdAndName(categoryId, brandName) != 0;
    }

    /**
     * 增加品牌
     * @param brandFormStr 品牌信息
     * @param brandImg 品牌图片
     * @return 是否成功
     */
    @Override
    public boolean addBrand(String brandFormStr, MultipartFile brandImg) {
        JSONObject brandFormJson = JSON.parseObject(brandFormStr);

        System.out.println("brandJson = " + brandFormJson);

        Integer categoryId = brandFormJson.getInteger("categoryId");
        Integer maxBrandId = brandMapper.queryMaxBrandIdByCategory(categoryId);// 根据 分区id 获取该分区最大的品牌号
        if (maxBrandId == null){
            maxBrandId = categoryId * 100;
        }

        Integer result = maxBrandId + 1;

        String logoPath = "/static/brand/" + categoryId + "/";// 生成路径
        try {
            String brandImgName = FileUtils.uploadBrandImg(brandImg, logoPath, result);
            Brand brand = new Brand();
            brand.setBrandId(result);
            brand.setBrandName(brandFormJson.getString("brandName"));
            brand.setDescribe(brandFormJson.getString("describe"));
            brand.setLogo(logoPath + brandImgName);
            brand.setState(brandFormJson.getInteger("state"));
            System.out.println("brand.getLogo() = " + brand.getLogo());
            System.out.println("maxBrandId = " + maxBrandId);

            int insertBrand = brandMapper.insertBrand(brand);
            int insertCategoryBrand = brandMapper.insertCategoryBrand(categoryId, brand.getBrandId());
            return insertBrand != 0 && insertCategoryBrand != 0;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
